package com.hd.trans.files.domain;

import android.text.TextUtils;

import androidx.lifecycle.MutableLiveData;

import com.hd.trans.files.bean.Audio;
import com.hd.trans.files.model.FileSortModel;
import com.hd.trans.files.sort.MediaSortHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: yangtianwen
 * Time: 2021/12/15
 * Des: 音频搜索业务处理
 */
public class SearchAudioUseCase extends BaseUseCase {

    private MutableLiveData<List<Audio>> mAudioDataObserver;

    public void audioSearch(List<Audio> audioData, String keyWord, String lastKeyWord,
                            FileSortModel.ModeItem sortMode,
                            Callback<String> callback) {
        final List<Audio> searchAudio = new ArrayList<>();
        if (TextUtils.equals(keyWord, lastKeyWord)) {
            // 防止相同关键词多次查询
            return;
        }
        if (TextUtils.isEmpty(keyWord)) {
            // 没有搜索关键词时显示原来的列表数据
            if (mAudioDataObserver != null) mAudioDataObserver.setValue(audioData);
            return;
        }
        for (Audio audio : audioData) {
            if (audio.getDisplay_name().toUpperCase().contains(keyWord.toUpperCase())) {
                searchAudio.add(audio);
            }
        }
        if (mAudioDataObserver != null) mAudioDataObserver.setValue(
                MediaSortHelper.getInstance().sortAudio(searchAudio, sortMode)
        );
        if (callback != null) callback.onValueChange(keyWord);
    }

    public SearchAudioUseCase addAudioDataObserver(MutableLiveData<List<Audio>> audioDataObserver) {
        this.mAudioDataObserver = audioDataObserver;
        return this;
    }
}
